
package com.jf.cloud.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.jf.cloud.api.leaf.dto.SegmentDTO;
import com.jf.cloud.api.leaf.dto.SegmentItemDTO;
import com.jf.cloud.api.leaf.feign.SegmentFeignClient;
import com.jf.cloud.api.multishop.bo.OrderChangeShopWalletAmountBO;
import com.jf.cloud.api.order.constant.OrderStatus;
import com.jf.cloud.common.constant.DistributedIdKey;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.order.bo.RefundReductionStockBO;
import com.jf.cloud.common.order.constant.OrderActivityType;
import com.jf.cloud.common.order.constant.OrderCloseType;
import com.jf.cloud.common.order.vo.OrderItemVO;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.rocketmq.config.RocketMqConstant;
import com.jf.cloud.common.util.PriceUtil;
import com.jf.cloud.order.mapper.OrderMapper;
import com.jf.cloud.order.mapper.OrderPreSaleInfoMapper;
import com.jf.cloud.order.model.Order;
import com.jf.cloud.order.model.OrderPreSaleInfo;
import com.jf.cloud.order.service.OrderPreSaleInfoService;
import com.jf.cloud.order.vo.OrderAndPreSaleVO;
import com.jf.cloud.common.order.vo.OrderPreSaleInfoVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 订单预售信息
 *
 * @author zz
 * @date 2022-08-17 16:36:47
 */
@Service
public class OrderPreSaleInfoServiceImpl implements OrderPreSaleInfoService {

    @Autowired
    private OrderPreSaleInfoMapper orderPreSaleInfoMapper;
    @Autowired
    private RocketMQTemplate orderRefundSuccessStockTemplate;
    @Autowired
    private RocketMQTemplate orderPreSaleFailSettlementTemplate;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private SegmentFeignClient segmentFeignClient;

    @Override
    public OrderPreSaleInfoVO getByOrderId(Long orderId) {
        return orderPreSaleInfoMapper.getByOrderId(orderId);
    }

    @Override
    public List<OrderPreSaleInfo> listByOrderIds(List<Long> orderIds) {

        return orderPreSaleInfoMapper.listByOrderIds(orderIds);
    }

    @Override
    public void saveBatch(List<OrderPreSaleInfo> orderPreSaleInfo) {
        if (CollUtil.isEmpty(orderPreSaleInfo)) {
            return;
        }
        List<SegmentItemDTO> segmentItemList = new ArrayList<>();
        segmentItemList.add(new SegmentItemDTO(DistributedIdKey.MALL4CLOUD_ORDER_PRE_SALE, orderPreSaleInfo.size()));

        // 获取订单id列表
        ServerResponseEntity<Map<String, List<Long>>> segmentIdResponse = segmentFeignClient.batchSegmentIdWithDateTime(new SegmentDTO(orderPreSaleInfo.get(0).getUserId(), segmentItemList));
        if (segmentIdResponse.isFail()) {
            throw new LuckException(segmentIdResponse.getMsg());
        }
        List<Long> ids = segmentIdResponse.getData().get(DistributedIdKey.MALL4CLOUD_ORDER_PRE_SALE);
        for (OrderPreSaleInfo preSaleInfo : orderPreSaleInfo) {
            preSaleInfo.setOrderPreSaleInfoId(ids.remove(0));
        }
        for (OrderPreSaleInfo preSaleInfo : orderPreSaleInfo) {
            orderPreSaleInfoMapper.save(preSaleInfo);
        }
//        orderPreSaleInfoMapper.saveBatch(orderPreSaleInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBatch(List<OrderPreSaleInfo> orderPreSaleInfoList) {
        for (OrderPreSaleInfo orderPreSaleInfo : orderPreSaleInfoList) {
            orderPreSaleInfoMapper.update(orderPreSaleInfo);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleBalanceTimeExpireOrder(List<Long> orderIds, List<Long> canalOrderList) {
        for (Long orderId : orderIds) {
            OrderAndPreSaleVO orderAndPreSaleVO = orderMapper.getBalanceTimeExpireByOrderId(orderId);
            // 幂等处理，不符合条件的跳过
            if (Objects.isNull(orderAndPreSaleVO)) {
                continue;
            }

            if (Objects.equals(orderAndPreSaleVO.getStatus(), OrderStatus.UNPAY.value())) {
                // 如果订单未支付的话，将订单设为取消状态
                canalOrderList.add(orderAndPreSaleVO.getOrderId());
                continue;
            }

            // 处理订单退款更新
            handleOrderRefund(orderAndPreSaleVO);
            // 库存回退
            OrderItemVO dbOrderItem = new OrderItemVO();
            List<RefundReductionStockBO> refundReductionStocks = new ArrayList<>();
            for (OrderItemVO orderItem : orderAndPreSaleVO.getOrderItems()) {
                if(orderItem.getMainGiveaway() == null || orderItem.getMainGiveaway() == 1 ){
                    dbOrderItem = orderItem;
                }
                RefundReductionStockBO refundReductionStockBO = new RefundReductionStockBO();
                refundReductionStockBO.setCount(orderItem.getCount());
                refundReductionStockBO.setOrderId(orderAndPreSaleVO.getOrderId());
                refundReductionStockBO.setShopId(orderAndPreSaleVO.getShopId());
                refundReductionStockBO.setSkuId(orderItem.getSkuId());
                refundReductionStockBO.setSpuId(orderItem.getSpuId());
                if(Objects.equals(orderAndPreSaleVO.getSupplierDeliveryType(),1) && !Objects.equals(orderAndPreSaleVO.getSupplierId(),0L)){
                    refundReductionStockBO.setSupplierProd(1);
                    refundReductionStockBO.setSkuId(orderItem.getSupplierSkuId());
                    refundReductionStockBO.setSpuId(orderItem.getSupplierSpuId());
                }
                refundReductionStocks.add(refundReductionStockBO);
            }

            // 通知还原库存
            SendStatus sendStatus = orderRefundSuccessStockTemplate.syncSend(RocketMqConstant.ORDER_REFUND_SUCCESS_STOCK_TOPIC, new GenericMessage<>(refundReductionStocks)).getSendStatus();
            if (!Objects.equals(sendStatus, SendStatus.SEND_OK)) {
                throw new LuckException(ResponseEnum.EXCEPTION);
            }

            // 订单超时未支付尾款 商家结算操作
            OrderChangeShopWalletAmountBO orderChangeShopWalletAmountBO = new OrderChangeShopWalletAmountBO();
            orderChangeShopWalletAmountBO.setActualTotal(orderAndPreSaleVO.getDepositAmount());
            orderChangeShopWalletAmountBO.setOrderId(orderAndPreSaleVO.getOrderId());
            orderChangeShopWalletAmountBO.setShopId(orderAndPreSaleVO.getShopId());
            // 平台佣金
            long platformCommission = PriceUtil.divideByBankerRounding((long) ((orderChangeShopWalletAmountBO.getActualTotal()) * dbOrderItem.getRate()), 100);
            orderChangeShopWalletAmountBO.setPlatformCommission(platformCommission);
            SendStatus status = orderPreSaleFailSettlementTemplate.syncSend(RocketMqConstant.ORDER_PRE_SALE_FAIL_SETTLEMENT_TOPIC, new GenericMessage<>(orderChangeShopWalletAmountBO)).getSendStatus();
            if (!Objects.equals(status, SendStatus.SEND_OK)) {
                throw new LuckException(ResponseEnum.EXCEPTION);
            }
        }
    }

    /**
     * 处理订单退款更新
     * @param orderAndPreSaleVO 订单信息
     */
    private void handleOrderRefund(OrderAndPreSaleVO orderAndPreSaleVO) {
        Order order = new Order();
        order.setOrderId(orderAndPreSaleVO.getOrderId());
        order.setStatus(OrderStatus.CLOSE.value());
        order.setCancelTime(new Date());
        order.setUpdateTime(new Date());
        order.setCloseType(OrderCloseType.REFUND.value());
        orderMapper.update(order);
    }
}
